﻿using Glorysoft.Auto.Xfw;
using Glorysoft.EAP.Contracts.MESClient.Models;
using Glorysoft.EAP.Core;
using Glorysoft.EAP.Core.Entities;
using Glorysoft.EAP.Core.Enums;
using Glorysoft.EAP.RC.EAPClient;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Serilog.Core;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace Glorysoft.EAP.Contracts.MESClient
{
    public class SMECMESClient
    {
        protected readonly Logger CimLogger;
        protected readonly Logger EAPlogger;
        protected readonly IConfiguration Config;
        EAPClientService ClientService = null;
        SoapClient soapClient;
        //private DBServer dbServer = null;
        public string Name => GetType().Name;
        public SMECMESClient()
        {
            CimLogger = XfwContext.LogManager.DbLogger;
            EAPlogger = XfwContext.LogManager.EapLogger;
            Config = XfwContext.Configuration as IConfiguration;
            ClientService = new EAPClientService();
            //dbServer = new DBServer();

        }

        public JObject recipeCheckRequest(string equipmentId, string waferId, string testProgram, string rcFlag)
        {
            try
            {
                JObject jo = new JObject();
                jo["equipmentId"] = equipmentId;
                jo["waferId"] = waferId;
                jo["testProgram"] = testProgram;
                jo["rcFlag"] = rcFlag;

                var baseurl = Config.GetSection("RmsUrl").Get<string>();
                var result = PostAsyncJson(baseurl + "/Recipe/RecipeCheck", jo.ToString()).GetAwaiter().GetResult();
                return JObject.Parse(result);
            }
            catch (Exception ex)
            {
                CimLogger.Error(ex.Message);
                return null;
            }

        }

        public static async Task<string> PostAsyncJson(string url, string json)
        {
            HttpClient client = new HttpClient();
            // 将JSON对象序列化为字符串

            var content = new StringContent(json, Encoding.UTF8, "application/json");

            try
            {
                // 发送POST请求
                var response = await client.PostAsync(url, content);
                response.EnsureSuccessStatusCode(); // 确保请求成功

                // 读取响应内容
                return await response.Content.ReadAsStringAsync();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return null;
            }
        }
        public UserResponse Login(string userName, string password, string facilityId)
        {
            //测试
            if (CItems.IsTest == "true")
            {
                UserResponse _return2 = new UserResponse();
                _return2.success = "True";
                _return2.msg = "";
                return _return2;
            }
            if (Dict.Current.EAPRunMode == RunMode.ManualOperation)
            {
                var messages = TranslateMsg.GetTranslation(CItems.ManualOperation);
                ClientService.ShowMessage("", MessageType.Info, messages, MessageOrigin.MES);
                CimLogger.Warning($"{Name}.Login()  The EAP has been switched Manual Operation ");
                return new UserResponse();
            }
            string UserNO=Config.GetSection("UserNO").Get<string>();
            if(!string.IsNullOrEmpty(UserNO))
            {
                if(userName== UserNO)
                {
                    UserResponse _return2 = new UserResponse();
                    _return2.success = "True";
                    _return2.msg = "";
                    return _return2;
                }
            }
            UserResponse _return = new UserResponse();
            // var baseurl = "http://10.190.220.101:7003/mycim2/services/LoginWebService?wsdl";
            var baseurl = Config.GetSection("MES").Get<string>().Split(";")[1];
            soapClient = new SoapClient(baseurl);
            Dictionary<string, string> userResponses = new Dictionary<string, string>();
            userResponses.Add("userName", userName);
            userResponses.Add("password", password);
            userResponses.Add("facilityId", facilityId);
            //Request Request = new Request();
            //Request.Header = new Header()
            //{
            //    MESSAGENAME = "login",
            //    USERNAME = "EAP",
            //    TRANSACTIONID = Guid.NewGuid().ToString(),
            //    SHOPNAME = "ASSMBLY"
            //};


            //RequestLogin login = new RequestLogin();
            //login.UserName = userName;
            //login.Password = password;
            //login.FacilityId = facilityId;
            //Request.Body = login;

            //var body = JsonConvert.SerializeObject(Request);
            ////发送接口
            //string req = "";
            //JsonReader readerJson = new JsonTextReader(new StringReader(JsonConvert.SerializeObject(body))); //针对转义字符特殊处理
            //while (readerJson.Read())
            //{
            //    req = readerJson.Value.ToString();
            //}
            var ret = soapClient.HttpRequestList("login", userResponses);

            //读取本地json文件
            //string ret = getJsonData("./MESInterfaceTest/" + request.EQUIPMENTID + "/TrackOut_Success.json");

            //写log
            //  string reqq = string.Empty;
            //foreach (char item in ret)
            //{
            //    reqq += item.ToString();
            //    if (item == ',')
            //    {
            //        reqq += "\r\n";
            //    }
            //    if (item == '{')
            //    {
            //        reqq += "\r\n";
            //    }
            //}
            CimLogger.Information($" MES<EAP.Login() Execute. Text:{ret}");
            JObject jsonObj = JObject.Parse(ret);
            var result = jsonObj["success"].ToString();
            var resultmsg = jsonObj["msg"].ToString();
            //反序列化Response
            //var result = JsonConvert.DeserializeObject<BaseResponses>(reqq);

            if (result == "True")
            {
                _return.success = result;
                _return.msg = resultmsg;
            }
            else
            {
                _return.success = result;
                _return.msg = resultmsg;
            }
            return _return;

        }

        public LotinfoResponse GetCarrierLotInfo(String lotid, string equipmentId, string userId, string facilityId)
        {
            LotinfoResponse _return = new LotinfoResponse();
            if (Dict.Current.EAPRunMode == RunMode.ManualOperation)
            {
                var messages = TranslateMsg.GetTranslation(CItems.ManualOperation);
                ClientService.ShowMessage("", MessageType.Info, messages, MessageOrigin.MES);
                CimLogger.Warning($"{Name}.GetCarrierLotInfo()  The EAP has been switched Manual Operation ");
                return _return;
            }
            // var baseurl = "http://10.190.220.108:7003/mycim2/services/JobManagementWebService?wsdl";
            var baseurl = Config.GetSection("MES").Get<string>().Split(";")[0];
            soapClient = new SoapClient(baseurl);
            Dictionary<string, string> carrierlotinfo = new Dictionary<string, string>();
            carrierlotinfo.Add("lotId", lotid);
            carrierlotinfo.Add("equipmentId", equipmentId);
            carrierlotinfo.Add("userId", userId);
            carrierlotinfo.Add("facilityId", facilityId);
            var ret = "";
            //发送http接口
            if (CItems.IsTest == "true")
            {
                //POC演示修改获取假数据
                ret = File.ReadAllText("./MockData/GetCarrierLotInfo.json");
            }
            else { 
            ret = soapClient.HttpRequestList("getCarrierLotInfo", carrierlotinfo);
            }
            var retLog = ret.Replace(",", ",\r\n").Replace("{", "{ \r\n");
            //取本地json文件
            //string ret = getJsonData("./MESInterfaceTest/" + EqpId + "/GetLotInfo_Success.json");
            //string reqq = string.Empty;
            //foreach (char item in ret)
            //{
            //    reqq += item.ToString();
            //    if (item == ',')
            //    {
            //        reqq += "\r\n";
            //    }
            //    if (item == '{')
            //    {
            //        reqq += "\r\n";
            //    }
            //}
            CimLogger.Information($"{lotid} MES<EAP.GetLotInfo() Execute. Text:{retLog}");
            JObject jsonObj = JObject.Parse(ret);
            var result = jsonObj["success"].ToString();
            var resultmsg = jsonObj["msg"].ToString();
            //反序列化Response
            //var result = JsonConvert.DeserializeObject<Response<object>>(ret);

            if (result == "True")
            {
                //resultmsg = resultmsg.Substring(1).Substring(0, resultmsg.Length - 2);
                //var jObject = JsonConvert.DeserializeObject<JObject>(resultmsg);
                //var ht_lotBaseInfo = jObject["lotBaseInfo"]?.ToString();

                //var jobject_unitsInfo = JsonConvert.DeserializeObject<JObject>(ht_lotBaseInfo);
                //var ht_unitsInfo = jobject_unitsInfo["unitsInfo"]?.ToString();

                //_return = JsonConvert.DeserializeObject<LotinfoResponse>(resultmsg);
                //_return.lotBaseInfo.UnitList = JsonConvert.DeserializeObject<List<Models.unitsInfo>>(ht_unitsInfo);

                resultmsg = resultmsg.Substring(1).Substring(0, resultmsg.Length - 2);
                var jObject = JsonConvert.DeserializeObject<JObject>(resultmsg);
                var ht_lotBaseInfo = jObject["lotBaseInfo"]?.ToString();

                var jobject_unitsInfo = JsonConvert.DeserializeObject<JObject>(ht_lotBaseInfo);
                var ht_unitsInfo = jobject_unitsInfo["unitsInfo"]?.ToString();

                var ht_mvOutParameterSet = jObject["mvOutParameterSet"]?.ToString();
                EAPlogger.Debug($"SMECMESClient.GetCarrierLotInfo() ht_mvOutParameterSet:{ht_mvOutParameterSet}");
                _return = JsonConvert.DeserializeObject<LotinfoResponse>(resultmsg);
                _return.lotBaseInfo.UnitList = JsonConvert.DeserializeObject<List<Models.unitsInfo>>(ht_unitsInfo);
                if (!string.IsNullOrEmpty(ht_mvOutParameterSet))
                {

                    var jobject_parameters = JsonConvert.DeserializeObject<JObject>(ht_mvOutParameterSet);
                    var ht_parameters = jobject_parameters["parameters"]?.ToString();
                    Dict.Current.parameterSet.parameterSetRrn = _return.mvOutParameterSetInfo.parameterSetRrn = jobject_parameters["parameterSetRrn"]?.ToString();
                    Dict.Current.parameterSet.parameterSetVersion = _return.mvOutParameterSetInfo.parameterSetVersion = jobject_parameters["parameterSetVersion"]?.ToString();
                    Dict.Current.parameterSet.parameterSetSpecRrn = _return.mvOutParameterSetInfo.parameterSetSpecRrn = jobject_parameters["parameterSetSpecRrn"]?.ToString();
                    Dict.Current.parameterSet.parameterSize = _return.mvOutParameterSetInfo.parameterSize = jobject_parameters["parameterSize"]?.ToString();
                    if (!string.IsNullOrEmpty(ht_parameters))
                    {
                        _return.mvOutParameterSetInfo.parameters = JsonConvert.DeserializeObject<List<parameters>>(ht_parameters);
                        Dict.Current.parameterSet.parametersinfo = JsonConvert.DeserializeObject<List<Glorysoft.EAP.Core.Entities.Odyssey.parameters>>(ht_parameters);


                        //var ht_parameter = ht_parameters.Substring(1).Substring(0, ht_parameters.Length - 2);

                        //var jobject_samplePrompts = JsonConvert.DeserializeObject<JObject>(ht_parameter);

                        //var ht_samplePrompts = jobject_samplePrompts["samplePrompts"]?.ToString();

                        //_return.mvOutParameterSetInfo.parametersinfo[0].samplePrompts = JsonConvert.DeserializeObject<List<samplePrompts>>(ht_samplePrompts);
                    }


                }

                _return.success = result;
                _return.msg = resultmsg;
            }
            else
            {
                _return.success = result;
                _return.msg = resultmsg.Replace("\n", "").Replace("\r", "");
            }

            return _return;
        }

        public LotinfoResponse GetCarrierLotInfoV2(String lotid, string equipmentId, string userId, string facilityId)
        {
            LotinfoResponse _return = new LotinfoResponse();
            if (Dict.Current.EAPRunMode == RunMode.ManualOperation)
            {
                var messages = TranslateMsg.GetTranslation(CItems.ManualOperation);
                ClientService.ShowMessage("", MessageType.Info, messages, MessageOrigin.MES);
                CimLogger.Warning($"{Name}.GetCarrierLotInfo()  The EAP has been switched Manual Operation ");
                return _return;
            }
            // var baseurl = "http://10.190.220.108:7003/mycim2/services/JobManagementWebService?wsdl";
            var baseurl = Config.GetSection("MES").Get<string>().Split(";")[0];
            soapClient = new SoapClient(baseurl);
            Dictionary<string, string> carrierlotinfo = new Dictionary<string, string>();
            carrierlotinfo.Add("carrierId", lotid);
            carrierlotinfo.Add("eqpId", equipmentId);
            carrierlotinfo.Add("userId", userId);


            //发送http接口 getCarrierLotInfo,InvokeCommonRVMessageByXMLMsgBody
            var ret = soapClient.HttpRequestListV2("InvokeCommonRVMessageByXMLMsgBody", carrierlotinfo);
            var retLog = ret.Replace(",", ",\r\n").Replace("{", "{ \r\n");
            //取本地json文件
            //string ret = getJsonData("./MESInterfaceTest/" + EqpId + "/GetLotInfo_Success.json");
            //string reqq = string.Empty;
            //foreach (char item in ret)
            //{
            //    reqq += item.ToString();
            //    if (item == ',')
            //    {
            //        reqq += "\r\n";
            //    }
            //    if (item == '{')
            //    {
            //        reqq += "\r\n";
            //    }
            //}
            CimLogger.Information($"{lotid} MES<EAP.GetLotInfo() Execute. Text:{retLog}");
            JObject jsonObj = JObject.Parse(ret);
            var result = jsonObj["msgBody"]["retCode"].ToString();
            var resultmsg = jsonObj["msgBody"]["retMessage"].ToString();
            //反序列化Response
            //var result = JsonConvert.DeserializeObject<Response<object>>(ret);

            if (result == "0")
            {
                if (jsonObj["msgBody"]["carrierInfo"] == null)
                {
                    var messages = TranslateMsg.GetTranslation("MesError");
                    ClientService.ShowMessage("", MessageType.Error, messages, MessageOrigin.MES);
                    CimLogger.Warning($"{Name}.GetCarrierLotInfo()  MES>返回数据异常!carrierInfo is null ");
                    return _return;
                }
                if (jsonObj["msgBody"]["carrierInfo"]["lotInfo"] == null)
                {
                    var messages = TranslateMsg.GetTranslation("MesError");
                    ClientService.ShowMessage("", MessageType.Error, messages, MessageOrigin.MES);
                    CimLogger.Warning($"{Name}.GetCarrierLotInfo()  MES>返回数据异常!carrierInfo.lotInfo is null ");
                    return _return;
                }
                //if (jsonObj["msgBody"]["carrierInfo"]["slotInfo"] == null)
                //{
                //    var messages = TranslateMsg.GetTranslation("MesError");
                //    ClientService.ShowMessage("", MessageType.Error, messages, MessageOrigin.MES);
                //    CimLogger.Warning($"{Name}.GetCarrierLotInfo()  MES>返回数据异常!carrierInfo.slotInfo is null ");
                //    return _return;
                //}
                _return.lotBaseInfo.productId = jsonObj["msgBody"]["carrierInfo"]["lotInfo"]["productId"].ToString();
                _return.lotBaseInfo.lotId = jsonObj["msgBody"]["carrierInfo"]["lotInfo"]["lotId"].ToString();
                _return.lotBaseInfo.recipeId = jsonObj["msgBody"]["carrierInfo"]["lotInfo"]["recipeId"].ToString();
                _return.lotBaseInfo.ppid = jsonObj["msgBody"]["carrierInfo"]["lotInfo"]["recipeId"].ToString();
                _return.lotBaseInfo.qty1 = jsonObj["msgBody"]["carrierInfo"]["lotInfo"]["qty"].ToString();
                //_return.lotBaseInfo.lotOwner = jsonObj["msgBody"]["carrierInfo"]["lotInfo"]["userId"].ToString();
                //resultmsg = resultmsg.Substring(1).Substring(0, resultmsg.Length - 2);
                //var jObject = JsonConvert.DeserializeObject<JObject>(resultmsg);
                //var ht_lotBaseInfo = jObject["lotBaseInfo"]?.ToString();

                //var jobject_unitsInfo = JsonConvert.DeserializeObject<JObject>(ht_lotBaseInfo);
                //var ht_unitsInfo = jobject_unitsInfo["unitsInfo"]?.ToString();

                //var ht_mvOutParameterSet = jObject["mvOutParameterSet"]?.ToString();
                //EAPlogger.Debug($"SMECMESClient.GetCarrierLotInfo() ht_mvOutParameterSet:{ht_mvOutParameterSet}");
                //_return = JsonConvert.DeserializeObject<LotinfoResponse>(resultmsg);
                //_return.lotBaseInfo.UnitList = JsonConvert.DeserializeObject<List<Models.unitsInfo>>(ht_unitsInfo);
                //if (!string.IsNullOrEmpty(ht_mvOutParameterSet))
                //{

                //    var jobject_parameters = JsonConvert.DeserializeObject<JObject>(ht_mvOutParameterSet);
                //    var ht_parameters = jobject_parameters["parameters"]?.ToString();
                //    Dict.Current.parameterSet.parameterSetRrn = _return.mvOutParameterSetInfo.parameterSetRrn = jobject_parameters["parameterSetRrn"]?.ToString();
                //    Dict.Current.parameterSet.parameterSetVersion = _return.mvOutParameterSetInfo.parameterSetVersion = jobject_parameters["parameterSetVersion"]?.ToString();
                //    Dict.Current.parameterSet.parameterSetSpecRrn = _return.mvOutParameterSetInfo.parameterSetSpecRrn = jobject_parameters["parameterSetSpecRrn"]?.ToString();
                //    Dict.Current.parameterSet.parameterSize = _return.mvOutParameterSetInfo.parameterSize = jobject_parameters["parameterSize"]?.ToString();
                //    if (!string.IsNullOrEmpty(ht_parameters))
                //    {
                //        _return.mvOutParameterSetInfo.parameters = JsonConvert.DeserializeObject<List<parameters>>(ht_parameters);
                //        Dict.Current.parameterSet.parametersinfo = JsonConvert.DeserializeObject<List<Glorysoft.EAP.Core.Entities.Odyssey.parameters>>(ht_parameters);


                //    }


                //}

                _return.success = "TRUE";
                _return.msg = resultmsg;
            }
            else
            {
                _return.success = "FAIL";
                _return.msg = resultmsg.Replace("\n", "").Replace("\r", "");
            }

            return _return;
        }


        public bool HoldEqpt(string chamberId, string equipmentId, string holdReasons, string userId, string facilityId)
        {
            LotinfoResponse _return = new LotinfoResponse();
            // var baseurl = "http://10.190.220.108:7003/mycim2/services/JobManagementWebService?wsdl";
            var baseurl = Config.GetSection("MES").Get<string>().Split(";")[0];
            soapClient = new SoapClient(baseurl);
            Dictionary<string, string> holdEqp = new Dictionary<string, string>();
            holdEqp.Add("Chamberid", chamberId);
            holdEqp.Add("equipmentId", equipmentId);
            holdEqp.Add("holdReasons", holdReasons);
            holdEqp.Add("userId", userId);
            holdEqp.Add("facilityId", facilityId);

            string ret = "";
            //发送http接口
            ret = soapClient.HttpRequestList("holdEqpt", holdEqp);
            if (string.IsNullOrEmpty(ret))
            {
                var messages = TranslateMsg.GetTranslation("MES 返回数据为空:MES returns null data ");
                ClientService.ShowMessage("", MessageType.Info, messages, MessageOrigin.MES);
                return false;
            }

            var retLog = ret.Replace(",", ",\r\n").Replace("{", "{ \r\n");
            CimLogger.Information($"{equipmentId} MES<EAP.HoldEqpt() Execute. Text:{retLog}");
            JObject jsonObj = JObject.Parse(ret);
            var result = jsonObj["result"].ToString();
            var resultmsg = jsonObj["msg"].ToString();
            //反序列化Response
            //var result = JsonConvert.DeserializeObject<Response<object>>(ret);

            if (result == "1")
            {
                return true;
            }



            return false;
        }



        public void uploadNonRTData(string facilityId, string userId, string equipmentId, string transData)
        {
            LotinfoResponse _return = new LotinfoResponse();
            // var baseurl = "http://10.190.220.108:7003/mycim2/services/JobManagementWebService?wsdl";
            var baseurl = Config.GetSection("MES").Get<string>().Split(";")[0];
            soapClient = new SoapClient(baseurl);
            Dictionary<string, string> holdEqp = new Dictionary<string, string>();
            holdEqp.Add("facilityId", facilityId);
            holdEqp.Add("userId", userId);
            holdEqp.Add("equipmentId", equipmentId);
            holdEqp.Add("transData", transData);

            string ret = "";
            //发送http接口
            ret = soapClient.HttpRequestList("uploadNonRTData", holdEqp);
            if (string.IsNullOrEmpty(ret))
            {
                var messages = TranslateMsg.GetTranslation("MES 返回数据为空:MES returns null data ");
                ClientService.ShowMessage("", MessageType.Info, messages, MessageOrigin.MES);
                return;
            }

            var retLog = ret.Replace(",", ",\r\n").Replace("{", "{ \r\n");
            CimLogger.Information($"{equipmentId} MES<EAP.uploadNonRTData() Execute. Text:{retLog}");

        }
    

        public TrackInResponse dispatchLotIn(string facilityId, string userId, string equipmentId, string lotIds, string transData)
        {
            TrackInResponse _return = new TrackInResponse();
            if (CItems.IsTest == "true")
            {
                _return.success = "True";
                _return.msg = "success";
                return _return;
            }
            if (Dict.Current.EAPRunMode == RunMode.ManualOperation)
            {
                var messages = TranslateMsg.GetTranslation(CItems.ManualOperation);
                ClientService.ShowMessage("", MessageType.Info, messages, MessageOrigin.MES);
                CimLogger.Warning($"{Name}.dispatchLotIn()  The EAP has been switched Manual Operation ");
                return _return;
            }
            //var baseurl = "http://10.190.220.102:7003/mycim2/services/JobManagementWebService?wsdl";
            var baseurl = Config.GetSection("MES").Get<string>().Split(";")[0];
            soapClient = new SoapClient(baseurl);
            Dictionary<string, string> trackin = new Dictionary<string, string>();
            trackin.Add("facilityId", facilityId);
            trackin.Add("userId", userId);
            trackin.Add("equipmentId", equipmentId);
            trackin.Add("lotIds", "[\"" + lotIds + "\"]");
            trackin.Add("transData", transData);
            //发送http接口
            var ret = soapClient.HttpRequestList("dispatchLot", trackin);

            //取本地json文件
            //string ret = getJsonData("./MESInterfaceTest/" + EqpId + "/GetLotInfo_Success.json");
            //string reqq = string.Empty;
            //foreach (char item in ret)
            //{
            //    reqq += item.ToString();
            //    if (item == ',')
            //    {
            //        reqq += "\r\n";
            //    }
            //    if (item == '{')
            //    {
            //        reqq += "\r\n";
            //    }
            //}
            CimLogger.Information($"{lotIds} MES<EAP.dispatchLotIn() Execute. Text:{ret}");
            JObject jsonObj = JObject.Parse(ret);
            var result = jsonObj["success"].ToString();
            var resultmsg = jsonObj["msg"].ToString();
            //读取本地json文件
            //string ret = getJsonData("./MESInterfaceTest/" + request.EQUIPMENTID + "/TrackIn_Success.json");
            //反序列化Response
            if (result == "True")
            {
                _return.success = result;
                _return.msg = resultmsg;
            }
            else
            {
                _return.success = result;
                _return.msg = resultmsg;
                // _return = JsonConvert.DeserializeObject<TrackInResponse>(resultmsg)
            }
            return _return;
        }
        public TrackOutResponse dispatchLotOut(string facilityId, string userId, string equipmentId, string lotIds, string transData)
        {
            TrackOutResponse _return = new TrackOutResponse();
            if (Dict.Current.EAPRunMode == RunMode.ManualOperation)
            {
                var messages = TranslateMsg.GetTranslation(CItems.ManualOperation);
                ClientService.ShowMessage("", MessageType.Info, messages, MessageOrigin.MES);
                CimLogger.Warning($"{Name}.dispatchLotOut()  The EAP has been switched Manual Operation ");
                return _return;
            }
            var baseurl = Config.GetSection("MES").Get<string>().Split(";")[0];
            soapClient = new SoapClient(baseurl);
            Dictionary<string, string> trackin = new Dictionary<string, string>();
            trackin.Add("facilityId", facilityId);
            trackin.Add("userId", userId);
            trackin.Add("equipmentId", equipmentId);
            trackin.Add("lotIds", "[\"" + lotIds + "\"]");
            trackin.Add("transData", transData);
            //发送http接口
            var ret = soapClient.HttpRequestList("dispatchLot", trackin);

            //取本地json文件
            //string ret = getJsonData("./MESInterfaceTest/" + EqpId + "/GetLotInfo_Success.json");
            //string reqq = string.Empty;
            //foreach (char item in ret)
            //{
            //    reqq += item.ToString();
            //    if (item == ',')
            //    {
            //        reqq += "\r\n";
            //    }
            //    if (item == '{')
            //    {
            //        reqq += "\r\n";
            //    }
            //}
            CimLogger.Information($"{lotIds} MES<EAP.dispatchLotOut() Execute. Text:{ret}");
            JObject jsonObj = JObject.Parse(ret);
            var result = jsonObj["success"].ToString();
            var resultmsg = jsonObj["msg"].ToString();
            //读取本地json文件
            //string ret = getJsonData("./MESInterfaceTest/" + request.EQUIPMENTID + "/TrackIn_Success.json");
            //反序列化Response
            if (result == "True")
            {
                _return.success = result;
                _return.msg = resultmsg;
            }
            else
            {
                _return.success = result;
                _return.msg = resultmsg;
            }
            return _return;
        }

        public BaseResponse LotTrackOut(RequestTrackOut request, string UserId)
        {
            BaseResponse _return = new BaseResponse();
            if (Dict.Current.EAPRunMode == RunMode.ManualOperation)
            {
                var messages = TranslateMsg.GetTranslation(CItems.ManualOperation);
                ClientService.ShowMessage("", MessageType.Info, messages, MessageOrigin.MES);
                CimLogger.Warning($"{Name}.LotTrackOut()  The EAP has been switched Manual Operation ");
                return _return;
            }
            var baseurl = Config.GetSection("MES").Get<string>();
            soapClient = new SoapClient(baseurl);
            Request Request = new Request();
            Request.Header = new Header()
            {
                MESSAGENAME = "TrackOut",
                USERNAME = UserId,
                TRANSACTIONID = Guid.NewGuid().ToString(),
                SHOPNAME = "ASSMBLY"
            };
            Request.Body = request;

            var body = JsonConvert.SerializeObject(Request);
            //发送接口
            string req = "";
            JsonReader readerJson = new JsonTextReader(new StringReader(JsonConvert.SerializeObject(body))); //针对转义字符特殊处理
            while (readerJson.Read())
            {
                req = readerJson.Value.ToString();
            }
            var ret = soapClient.HttpRequest("execute", req);

            //读取本地json文件
            //string ret = getJsonData("./MESInterfaceTest/" + request.EQUIPMENTID + "/TrackOut_Success.json");

            //写log
            //string reqq = string.Empty;
            //foreach (char item in ret)
            //{
            //    reqq += item.ToString();
            //    if (item == ',')
            //    {
            //        reqq += "\r\n";
            //    }
            //    if (item == '{')
            //    {
            //        reqq += "\r\n";
            //    }
            //}
            CimLogger.Information($" MES<EAP.LotTrackOut() Execute. Text:{ret}");

            //反序列化Response
            var result = JsonConvert.DeserializeObject<Response<Object>>(ret);
            if (result.Header.RETURNCODE == "0")
            {
                _return.success = true;
            }
            else
            {
                _return.success = false;
                _return.msg = result.Header.RETURNMESSAGE.ToString();
            }
            return _return;
        }

        public holdMixrunLotResponse holdMixrunLot(string facilityId, string userId, string equipmentId, string lotIds, string holdGroup, string holdCode, string holdReasons)
        {
            holdMixrunLotResponse _return = new holdMixrunLotResponse();
            if (Dict.Current.EAPRunMode == RunMode.ManualOperation)
            {
                var messages = TranslateMsg.GetTranslation(CItems.ManualOperation);
                ClientService.ShowMessage("", MessageType.Info, messages, MessageOrigin.MES);
                CimLogger.Warning($"{Name}.holdMixrunLot()  The EAP has been switched Manual Operation ");
                return _return;
            }
            var baseurl = Config.GetSection("MES").Get<string>().Split(";")[0];
            soapClient = new SoapClient(baseurl);
            Dictionary<string, string> holdlot = new Dictionary<string, string>();
            holdlot.Add("facilityId", facilityId);
            holdlot.Add("userId", userId);
            holdlot.Add("equipmentId", equipmentId);
            holdlot.Add("mixrunLotId", lotIds);
            holdlot.Add("holdGroup", holdGroup);
            holdlot.Add("holdCode", holdCode);
            holdlot.Add("holdReasons", holdReasons);

            //发送http接口
            var ret = soapClient.HttpRequestList("holdMixrunLot", holdlot);
            CimLogger.Information($"{lotIds} MES<EAP.holdMixrunLot() Execute. Text:{ret}");
            JObject jsonObj = JObject.Parse(ret);
            var result = jsonObj["success"].ToString();
            var resultmsg = jsonObj["msg"].ToString();
            if (result == "True")
            {
                _return.success = result;
                _return.msg = resultmsg;
            }
            else
            {
                _return.success = result;
                _return.msg = resultmsg;

            }
            return _return;
        }

        public holdMixrunLotResponse holdRuningLot(string facilityId, string userId, string equipmentId, string lotIds, string holdGroup, string holdCode, string holdReasons)
        {
            holdMixrunLotResponse _return = new holdMixrunLotResponse();
            if (Dict.Current.EAPRunMode == RunMode.ManualOperation)
            {
                var messages = TranslateMsg.GetTranslation(CItems.ManualOperation);
                ClientService.ShowMessage("", MessageType.Info, messages, MessageOrigin.MES);
                CimLogger.Warning($"{Name}.holdRuningLot()  The EAP has been switched Manual Operation ");
                return _return;
            }
            var baseurl = Config.GetSection("MES").Get<string>().Split(";")[0];
            soapClient = new SoapClient(baseurl);
            Dictionary<string, string> holdlot = new Dictionary<string, string>();
            holdlot.Add("facilityId", facilityId);
            holdlot.Add("userId", userId);
            holdlot.Add("equipmentId", equipmentId);
            holdlot.Add("lotId", lotIds);
            holdlot.Add("holdGroup", holdGroup);
            holdlot.Add("holdCode", holdCode);
            holdlot.Add("holdReasons", holdReasons);

            //发送http接口
            var ret = soapClient.HttpRequestList("holdRunningLot", holdlot);
            CimLogger.Information($"{lotIds} MES<EAP.holdRunningLot() Execute. Text:{ret}");
            JObject jsonObj = JObject.Parse(ret);
            var result = jsonObj["success"].ToString();
            var resultmsg = jsonObj["msg"].ToString();
            if (result.ToUpper() == "TRUE")
            {
                _return.success = result;
                _return.msg = resultmsg;
            }
            else
            {
                _return.success = result;
                _return.msg = resultmsg;

            }
            return _return;
        }
    }
}
